<template>
  <div class="checkout-container">
    <div class="checkout-header">
      <h2>订单结算</h2>
      <el-steps :active="activeStep" finish-status="success" simple>
        <el-step title="确认订单" />
        <el-step title="选择支付方式" />
        <el-step title="完成支付" />
      </el-steps>
    </div>

    <!-- 步骤1: 确认订单 -->
    <div v-if="activeStep === 0" class="checkout-step">
      <!-- 收货地址选择 -->
      <div class="address-section section-card">
        <div class="section-header">
          <i class="fas fa-map-marker-alt"></i>
          <h3>收货地址</h3>
        </div>
        <div v-if="!selectedAddress" class="empty-address">
          <p>您还没有选择收货地址</p>
          <el-button type="primary" @click="addressDialogVisible = true">选择地址</el-button>
        </div>
        <div v-else class="selected-address">
          <div class="address-info">
            <p class="address-name">{{ selectedAddress.consignee }} <span class="address-phone">{{ selectedAddress.phone }}</span></p>
            <p class="address-detail">{{ selectedAddress.detail }}</p>
          </div>
          <el-button type="text" @click="addressDialogVisible = true">更换</el-button>
        </div>
      </div>

      <!-- 购物车商品列表 -->
      <div class="cart-section section-card">
        <div class="section-header">
          <i class="fas fa-shopping-cart"></i>
          <h3>商品清单</h3>
        </div>
        <div v-if="cartItems.length === 0" class="empty-cart">
          <p>您的购物车是空的，请先添加商品</p>
          <el-button type="primary" @click="$router.push('/home/products')">去选购</el-button>
        </div>
        <div v-else class="cart-items">
          <div class="cart-header">
            <span class="col-product">商品信息</span>
            <span class="col-price">单价</span>
            <span class="col-quantity">数量</span>
            <span class="col-subtotal">小计</span>
          </div>
          <div v-for="item in cartItems" :key="item.id" class="cart-item">
            <div class="col-product">
              <div class="product-image">
                <img :src="getFullImageUrl(item.image)" :alt="item.name">
              </div>
              <div class="product-info">
                <h4>{{ item.name }}</h4>
                <p v-if="item.dishFlavor" class="flavor-tag">{{ formatFlavor(item.dishFlavor) }}</p>
              </div>
            </div>
            <div class="col-price">¥{{ item.amount }}</div>
            <div class="col-quantity">{{ item.number }}</div>
            <div class="col-subtotal">¥{{ (item.amount * item.number).toFixed(2) }}</div>
          </div>
        </div>
      </div>

      <!-- 订单备注 -->
      <div class="remark-section section-card">
        <div class="section-header">
          <i class="fas fa-comment-alt"></i>
          <h3>订单备注</h3>
        </div>
        <el-input
            v-model="orderRemark"
            type="textarea"
            :rows="2"
            placeholder="请输入订单备注信息（选填）"
            maxlength="100"
            show-word-limit
        />
      </div>

      <!-- 订单金额 -->
      <div class="order-summary section-card">
        <div class="summary-item">
          <span>商品总额：</span>
          <span>¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>配送费：</span>
          <span>¥{{ deliveryFee.toFixed(2) }}</span>
        </div>
        <div class="summary-total">
          <span>实付金额：</span>
          <span class="total-price">¥{{ (totalAmount + deliveryFee).toFixed(2) }}</span>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="checkout-actions">
        <el-button @click="$router.push('/home/cart')">返回购物车</el-button>
        <el-button type="primary" @click="goToPayment" :disabled="!canProceed">
          去支付
        </el-button>
      </div>
    </div>

    <!-- 步骤2: 选择支付方式 -->
    <div v-if="activeStep === 1" class="checkout-step">
      <div class="payment-section section-card">
        <div class="section-header">
          <i class="fas fa-credit-card"></i>
          <h3>选择支付方式</h3>
        </div>
        <div class="payment-options">
          <div
              class="payment-option"
              :class="{ active: payMethod === 1 }"
              @click="payMethod = 1"
          >
            <i class="fab fa-weixin"></i>
            <span>微信支付</span>
          </div>
          <div
              class="payment-option"
              :class="{ active: payMethod === 2 }"
              @click="payMethod = 2"
          >
            <i class="fab fa-alipay"></i>
            <span>支付宝</span>
          </div>
        </div>
      </div>

      <!-- 订单确认信息 -->
      <div class="order-confirm section-card">
        <div class="section-header">
          <i class="fas fa-file-invoice"></i>
          <h3>订单信息确认</h3>
        </div>
        <div class="confirm-info">
          <div class="confirm-item">
            <span class="label">收货人：</span>
            <span>{{ selectedAddress?.consignee }}</span>
          </div>
          <div class="confirm-item">
            <span class="label">联系电话：</span>
            <span>{{ selectedAddress?.phone }}</span>
          </div>
          <div class="confirm-item">
            <span class="label">收货地址：</span>
            <span>{{ selectedAddress?.detail }}</span>
          </div>
          <div class="confirm-item">
            <span class="label">商品数量：</span>
            <span>{{ totalItems }}件</span>
          </div>
          <div class="confirm-item">
            <span class="label">订单备注：</span>
            <span>{{ orderRemark || '无' }}</span>
          </div>
          <div class="confirm-item">
            <span class="label">支付方式：</span>
            <span>{{ payMethod === 1 ? '微信支付' : '支付宝' }}</span>
          </div>
          <div class="confirm-item total">
            <span class="label">应付金额：</span>
            <span class="price">¥{{ (totalAmount + deliveryFee).toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="checkout-actions">
        <el-button @click="activeStep = 0">上一步</el-button>
        <el-button type="primary" @click="submitOrder">
          确认支付
        </el-button>
      </div>
    </div>

    <!-- 步骤3: 支付完成 -->
    <div v-if="activeStep === 2" class="checkout-step">
      <div class="payment-success section-card">
        <div class="success-icon">
          <i class="fas fa-check-circle"></i>
        </div>
        <h2>支付成功</h2>
        <p>您的订单已支付成功，我们将尽快为您配送</p>
        <p class="order-number">订单号：{{ orderNumber }}</p>
        <div class="success-actions">
          <el-button @click="$router.push('/home/orders')">查看订单</el-button>
          <el-button type="primary" @click="$router.push('/home/products')">
            继续购物
          </el-button>
        </div>
      </div>
    </div>

    <!-- 地址选择对话框 -->
    <el-dialog
        v-model="addressDialogVisible"
        title="选择收货地址"
        width="600px"
    >
      <div class="address-list">
        <div
            v-for="address in addressList"
            :key="address.id"
            class="address-item"
            :class="{ active: tempSelectedAddressId === address.id }"
            @click="tempSelectedAddressId = address.id"
        >
          <div class="address-content">
            <div class="address-header">
              <span class="name">{{ address.consignee }}</span>
              <span class="phone">{{ address.phone }}</span>
              <span v-if="address.isDefault" class="default-tag">默认</span>
            </div>
            <div class="address-body">
              {{ address.detail }}
            </div>
          </div>
          <div class="address-actions">
            <el-radio v-model="tempSelectedAddressId" :label="address.id"></el-radio>
          </div>
        </div>
        <div v-if="addressList.length === 0" class="empty-address-list">
          <p>您还没有添加收货地址</p>
          <el-button type="primary" @click="goToAddAddress">添加新地址</el-button>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddress">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus';
import {getCartList, clearCart} from '@/api/cart';
import {getAddressList} from '@/api/addressBook';
import {createOrder} from '@/api/order';
import {fileViewPath} from "@/utils/file";

const router = useRouter();

// 步骤控制
const activeStep = ref(0);

// 地址相关
const addressList = ref([]);
const selectedAddress = ref(null);
const tempSelectedAddressId = ref(null);
const addressDialogVisible = ref(false);

// 购物车相关
const cartItems = ref([]);
const orderRemark = ref('');
const payMethod = ref(1); // 默认微信支付
const deliveryFee = ref(5); // 配送费
const orderNumber = ref('');

// 计算总金额
const totalAmount = computed(() => {
  return cartItems.value.reduce((sum, item) => {
    return sum + (item.amount * item.number);
  }, 0);
});

// 计算总商品数
const totalItems = computed(() => {
  return cartItems.value.reduce((sum, item) => {
    return sum + item.number;
  }, 0);
});

// 是否可以进行下一步
const canProceed = computed(() => {
  return selectedAddress.value && cartItems.value.length > 0;
});

// 获取购物车数据
const fetchCartItems = async () => {
  try {
    const res = await getCartList();
    if (res.code === '200') {
      cartItems.value = res.data || [];
    } else {
      ElMessage.error(res.msg || '获取购物车数据失败');
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error);
    ElMessage.error('获取购物车数据失败');
  }
};

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const res = await getAddressList();
    if (res.code === '200') {
      addressList.value = res.data || [];

      // 如果有默认地址，自动选中
      const defaultAddress = addressList.value.find(addr => addr.isDefault === 1);
      if (defaultAddress) {
        selectedAddress.value = defaultAddress;
        tempSelectedAddressId.value = defaultAddress.id;
      } else if (addressList.value.length > 0) {
        // 否则选中第一个地址
        selectedAddress.value = addressList.value[0];
        tempSelectedAddressId.value = addressList.value[0].id;
      }
    } else {
      ElMessage.error(res.msg || '获取地址列表失败');
    }
  } catch (error) {
    console.error('获取地址列表失败:', error);
    ElMessage.error('获取地址列表失败');
  }
};

// 确认选择的地址
const confirmAddress = () => {
  const address = addressList.value.find(addr => addr.id === tempSelectedAddressId.value);
  if (address) {
    selectedAddress.value = address;
    addressDialogVisible.value = false;
  } else {
    ElMessage.warning('请选择一个收货地址');
  }
};

// 前往添加地址页面
const goToAddAddress = () => {
  addressDialogVisible.value = false;
  router.push('/home/profile');
};

// 前往支付页面
const goToPayment = () => {
  if (!selectedAddress.value) {
    ElMessage.warning('请选择收货地址');
    return;
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品');
    return;
  }

  activeStep.value = 1;
};

// 提交订单
// 提交订单
const submitOrder = async () => {
  try {
    // 构建订单数据
    const orderData = {
      addressBookId: selectedAddress.value.id,
      payMethod: payMethod.value,
      remark: orderRemark.value,
      amount: totalAmount.value + deliveryFee.value,
      phone: selectedAddress.value.phone,
      address: selectedAddress.value.detail,
      userName: selectedAddress.value.consignee,
      consignee: selectedAddress.value.consignee,
      // 添加订单明细数据
      orderDetails: cartItems.value.map(item => {
        return {
          name: item.name,
          image: item.image,
          dishId: item.dishId || null,
          setmealId: item.setmealId || null,
          dishFlavor: item.dishFlavor || null,
          number: item.number,
          amount: item.amount
        };
      })
    };

    const res = await createOrder(orderData);
    console.log("res=",res)
    if (res.code === '200') {
      // 订单创建成功
      orderNumber.value = res.data;

      // 清空购物车
      await clearCart();

      // 显示支付成功页面
      activeStep.value = 2;

      // 触发购物车数量更新
      window.dispatchEvent(new Event('cart-updated'));
    } else {
      ElMessage.error(res.msg || '创建订单失败');
    }
  } catch (error) {
    console.error('提交订单失败:', error);
    ElMessage.error('提交订单失败');
  }
};

// 格式化口味信息
const formatFlavor = (flavorJson) => {
  try {
    const flavors = JSON.parse(flavorJson);
    return Object.entries(flavors)
        .map(([key, value]) => `${key}: ${value}`)
        .join(', ');
  } catch (e) {
    return flavorJson;
  }
};

// 获取图片完整URL
const getFullImageUrl = (imagePath) => {
  if (!imagePath) return '';
  return `${fileViewPath}${formatImagePath(imagePath)}`;
};

// 格式化图片路径
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/');
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCartItems();
  fetchAddressList();
});
</script>

<style scoped>
.checkout-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.checkout-header {
  margin-bottom: 30px;
  text-align: center;
}

.checkout-header h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
}

.section-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header i {
  margin-right: 10px;
  color: #ff6b6b;
  font-size: 18px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

/* 地址样式 */
.empty-address {
  text-align: center;
  padding: 20px 0;
  color: #999;
}

.selected-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-info {
  flex: 1;
}

.address-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.address-phone {
  margin-left: 10px;
  color: #666;
}

.address-detail {
  color: #666;
  margin: 0;
}

/* 购物车样式 */
.cart-header {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  font-weight: bold;
  color: #666;
}

.cart-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
}

.col-product {
  flex: 3;
  display: flex;
  align-items: center;
}

.col-price, .col-quantity, .col-subtotal {
  flex: 1;
  text-align: center;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info h4 {
  margin: 0 0 5px;
  font-size: 16px;
}

.flavor-tag {
  display: inline-block;
  background-color: #f8f8f8;
  color: #666;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin: 0;
}

.empty-cart {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

/* 订单摘要 */
.order-summary {
  margin-top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  font-weight: bold;
}

.total-price {
  color: #ff6b6b;
  font-size: 20px;
}

/* 底部操作栏 */
.checkout-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}

.checkout-actions button {
  margin-left: 10px;
}

/* 支付方式 */
.payment-options {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.payment-option {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-option i {
  font-size: 36px;
  margin-bottom: 10px;
}

.payment-option.active {
  border-color: #ff6b6b;
  color: #ff6b6b;
}

.payment-option:hover {
  border-color: #ff6b6b;
}

.payment-option i.fa-weixin {
  color: #07c160;
}

.payment-option i.fa-alipay {
  color: #1677ff;
}

.payment-option.active i {
  color: #ff6b6b;
}

/* 订单确认信息 */
.confirm-item {
  margin-bottom: 10px;
  display: flex;
}

.confirm-item .label {
  width: 100px;
  color: #666;
}

.confirm-item.total {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  font-weight: bold;
}

.confirm-item .price {
  color: #ff6b6b;
  font-size: 18px;
}

/* 支付成功 */
.payment-success {
  text-align: center;
  padding: 40px 20px;
}

.success-icon {
  font-size: 60px;
  color: #52c41a;
  margin-bottom: 20px;
}

.payment-success h2 {
  color: #52c41a;
  margin-bottom: 15px;
}

.order-number {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
  margin: 20px 0;
  font-family: monospace;
  font-size: 16px;
}

.success-actions {
  margin-top: 30px;
}

/* 地址选择对话框 */
.address-list {
  max-height: 400px;
  overflow-y: auto;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #ff6b6b;
}

.address-item.active {
  border-color: #ff6b6b;
  background-color: #fff9f9;
}

.address-content {
  flex: 1;
}

.address-header {
  margin-bottom: 5px;
}

.address-header .name {
  font-weight: bold;
  margin-right: 10px;
}

.address-header .phone {
  color: #666;
}

.default-tag {
  background-color: #ff6b6b;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 10px;
}

.address-body {
  color: #666;
}

.empty-address-list {
  text-align: center;
  padding: 30px 0;
  color: #999;
}
</style>